package com.gofun.report.util;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.params.ClientPNames;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.DefaultHttpRequestRetryHandler;
import org.apache.http.impl.conn.PoolingClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class HttpNewClient {
	private static Logger log = LoggerFactory.getLogger(HttpNewClient.class);
	static HttpParams params = new BasicHttpParams();
	static PoolingClientConnectionManager conMgr = new PoolingClientConnectionManager();
	static DefaultHttpClient httpClient = null;
	//设置连接超时时间
	static int CONNECTION_TIMEOUT = 2 * 1000; //设置请求超时2秒钟 根据业务调整
	static int SO_TIMEOUT = 2 * 1000; //设置等待数据超时时间2秒钟 根据业务调整
	//定义了当从ClientConnectionManager中检索ManagedClientConnection实例时使用的毫秒级的超时时间
	//这个参数期望得到一个java.lang.Long类型的值。如果这个参数没有被设置，默认等于CONNECTION_TIMEOUT，因此一定要设置
	static long CONN_MANAGER_TIMEOUT = 500L; //该值就是连接不够用的时候等待超时时间，一定要设置，而且不能太大 ()
	static {
		params.setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, CONNECTION_TIMEOUT);
		params.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, SO_TIMEOUT);
		params.setLongParameter(ClientPNames.CONN_MANAGER_TIMEOUT, CONN_MANAGER_TIMEOUT);
		//在提交请求之前 测试连接是否可用
		params.setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, true);
		
		conMgr.setMaxTotal(200); //设置整个连接池最大连接数 根据自己的场景决定
		//是路由的默认最大连接（该值默认为2），限制数量实际使用DefaultMaxPerRoute并非MaxTotal。
		//设置过小无法支持大并发(ConnectionPoolTimeoutException: Timeout waiting for connection from pool)，路由是对maxTotal的细分。
		conMgr.setDefaultMaxPerRoute(conMgr.getMaxTotal());//（目前只有一个路由，因此让他等于最大值）
		//另外设置http client的重试次数，默认是3次；当前是禁用掉（如果项目量不到，这个默认即可）
		httpClient = new DefaultHttpClient(conMgr);
		httpClient.setHttpRequestRetryHandler(new DefaultHttpRequestRetryHandler(0, false));
	}
	
	public static String doGet(String url) throws IOException {
		HttpResponse response = null;
		HttpEntity entity = null;
		String returnStr = null;
		
		try {
			HttpGet get = new HttpGet(url);
			get.setParams(params);
			response = httpClient.execute(get);
			entity = response.getEntity();
			
			if (response.getStatusLine().getStatusCode() == 200) {
				entity = response.getEntity();
				returnStr = EntityUtils.toString(entity, HTTP.UTF_8);
			}
			
			return returnStr;
		} catch (Exception e) {
			// 处理异常
			log.error(e.getMessage(),e);
		} finally {
			if (response != null) {
				EntityUtils.consume(response.getEntity()); // 会自动释放连接
			}
		}
		return null;
	}
	
	
	public static String doPost(String url, Map<String, Object> paramsMap) throws IOException {
		HttpResponse response = null;
		HttpEntity entity = null;
		String returnStr = null;
		try {
			HttpPost post = new HttpPost(url);
			post.setParams(params);
			
		    List <NameValuePair> nameValuePair = new ArrayList<NameValuePair>();  
				if (paramsMap != null && !paramsMap.isEmpty()) {
					for (String key : paramsMap.keySet()) {
						nameValuePair.add(new BasicNameValuePair(key, paramsMap.get(key).toString()));
					}
				}
			post.setEntity(new UrlEncodedFormEntity(nameValuePair,HTTP.UTF_8));  
			
			response = httpClient.execute(post);
			
			if (response.getStatusLine().getStatusCode() == 200) {
				entity = response.getEntity();
				returnStr = EntityUtils.toString(entity, HTTP.UTF_8);
			}
			return returnStr;
		} catch (Exception e) {
			// 处理异常
			log.error(e.getMessage(),e);
		} finally {
			if (response != null) {
				EntityUtils.consume(response.getEntity()); // 会自动释放连接
			}
		}
		return null;
	}
	
	
	
	public static void main(String[] args) throws IOException {
		for(int i = 0;i<10000;i++){
			System.out.println(doPost("http://test.api.shouqiev.net/app/setting.json",null)); 
		}
		
	}
}
